package com.luter.heimdall.samples.webflux.webfluxdemo.config;

import com.luter.heimdall.core.exception.HeimdallUnauthenticatedException;
import com.luter.heimdall.core.exception.HeimdallUnauthorizedException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufMono;

import java.nio.charset.StandardCharsets;

@Component
public class CustomErrorWebHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        if (ex instanceof HeimdallUnauthenticatedException) {
            status = HttpStatus.UNAUTHORIZED;
        }
        if (ex instanceof HeimdallUnauthorizedException) {
            status = HttpStatus.FORBIDDEN;
        }
        final DataBuffer write = response.bufferFactory()
                .allocateBuffer().write(ex.getMessage().getBytes(StandardCharsets.UTF_8));
        response.setStatusCode(status);
        response.getHeaders().setContentType(MediaType.TEXT_HTML);
        return response.writeAndFlushWith(Mono.just(ByteBufMono.just(write)));
    }
}
